//
//  STSearchBar.m
//  OCVVeibo
//
//  Created by leergou on 16/7/25.
//  Copyright © 2016年 WhiteHouse. All rights reserved.
//

#import "STSearchBar.h"

@interface STSearchBar ()

@property (nonatomic,strong) UITextField *textField;

@property (nonatomic,strong) UIButton *cancelButton;

@end

@interface STSearchBar ()<UITextFieldDelegate>

@end

@implementation STSearchBar


- (instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 35)]) {
        
        [self setupUI];
    }
    return self;
}

#pragma mark - setupUI
- (void)setupUI{
    
    // 添加控件
    [self addSubview:self.cancelButton];
    [self addSubview:self.textField];
    // 添加约束
    [self.textField makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.bottom.equalTo(self);
        make.trailing.equalTo(self);
    }];
    
    [self.cancelButton makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.trailing.equalTo(self);
        make.width.equalTo(50);
    }];
}

#pragma mark - textField delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{

    [self.textField updateConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self).offset(-50);
    }];
    
    // 刷新UI
    [UIView animateWithDuration:0.25 animations:^{
        [self layoutIfNeeded];
    }];
}


#pragma mark - cancel
- (void)cancelEdite{
    
    [self.textField resignFirstResponder];
    
    [self.textField updateConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self);
    }];
    
    // 刷新UI
    [UIView animateWithDuration:0.25 animations:^{
        [self layoutIfNeeded];
    }];
    
}




#pragma mark - lazy
- (UITextField *)textField{
    if (!_textField) {
        UIImageView *leftView = [[UIImageView alloc] initWithImageName:@"searchbar_textfield_search_icon"];
        leftView.contentMode = UIViewContentModeCenter;
        
        _textField = [[UITextField alloc] init];
        _textField.leftView = leftView;
        _textField.leftViewMode = UITextFieldViewModeAlways;
        _textField.delegate = self;
        _textField.placeholder = @"搜索万万千";
        _textField.backgroundColor = [UIColor whiteColor];
    }
    return _textField;
}

- (UIButton *)cancelButton{
    if (!_cancelButton) {
        _cancelButton = [[UIButton alloc] initWithTitle:@"取消" target:self action:@selector(cancelEdite)];
        _cancelButton.backgroundColor = [UIColor greenColor];
    }
    return _cancelButton;
}




@end
